package org.shiro.config.shiro;

import cn.hutool.core.util.StrUtil;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

import static org.shiro.basic.constant.ShiroConstant.HEADER;

/**
 * 自定义SessionManager管理器
 *
 * @author LiKun
 * @date 2021/11/2 13:41
 */
public class ShiroSessionManager extends DefaultWebSessionManager {
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";
    private static final Logger logger = LoggerFactory.getLogger(ShiroSessionManager.class);

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        // 获取指定的请求头信息(Token)
        String token = ((HttpServletRequest) request).getHeader(HEADER);

        logger.info("从请求头信息中获取SessionID：{}", token);

        if (StrUtil.isNotEmpty(token)) {
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, token);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);

            return token;
        }

        return super.getSessionId(request, response);
    }
}
